"use client";

import React, { useState, useEffect, useRef, useCallback } from "react";
import Link from "next/link";
import { LeftOutlined, MessageOutlined, ExclamationCircleOutlined, HomeOutlined } from "@ant-design/icons";
import { Card, Button, List, Avatar, Typography, Space } from "antd";
import { useRouter, useParams } from "next/navigation";
import { useUser } from "../../context/userContext";
import api from "../../utils/api";

const { Title, Text } = Typography;

// 统一的卡片样式
const cardStyle = {
  backgroundColor: "white",
  borderRadius: 12,
  boxShadow: "0 2px 8px rgba(0, 0, 0, 0.09)",
  transition: "all 0.3s ease",
  marginBottom: 16,
  ":hover": {
    boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
    transform: "translateY(-2px)",
  },
};

// 加载中状态样式
const loadingStyle = {
  display: "flex",
  justifyContent: "center",
  padding: "16px 0",
  color: "#7A6E6E",
};

export default function ProfilePage() {
  const [loading, setLoading] = useState(true);
  const [initialLoading, setInitialLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("posts");
  const [authorPosts, setAuthorPosts] = useState([]);
  const [author, setAuthor] = useState(null);
  const [authorIcon, setAuthorIcon] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize] = useState(4); // 减少每页数量，便于测试滚动加载
  const [total, setTotal] = useState(0);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const router = useRouter();
  const { user } = useUser();
  const { authorId } = useParams();
  const contentRef = useRef(null); // 内容区域引用，用于滚动监听

  useEffect(() => {
    const fetchAuthor = async () => {
      try {
        const response = await api.get("/users/info", {
          params: { id: authorId },
        });
        if (response.status === 200) {
          setAuthor(response.data);
          setAuthorIcon(response.data.icon);
        }
      } catch (error) {
        console.error("获取作者信息失败:", error);
        router.push("/404");
      }
    };

    if (authorId) {
      fetchAuthor();
    }
  }, [authorId, router]);

  useEffect(() => {
    if (authorId) {
      fetchData();
    }
  }, [authorId, page, activeTab]);

  // 获取用户的帖子数据
  const fetchData = async (isMore = false) => {
    try {
      if (isLoadingMore) return; // 如果正在加载更多，不重复请求
      
      setIsLoadingMore(true);
      let url;
      let params = {
        page: String(isMore ? page + 1 : page),
        pageSize: String(pageSize),
      };

      switch (activeTab) {
        case "posts":
          url = "/posts/author";
          params = {
            ...params,
            authorId: authorId,
          };
          break;

        default:
          break;
      }

      const headers =
        user && user.access_token
          ? { Authorization: `Bearer ${user.access_token}` }
          : {};
      const response = await api.get(url, { params, headers });

      if (response.status === 200) {
        switch (activeTab) {
          case "posts":
            const postsData = Array.isArray(response.data.posts)
              ? response.data.posts
              : [];
            const totalCount = response.data.total || 0;
            
            // 加载更多时合并数据，否则替换数据
            setAuthorPosts(isMore ? [...authorPosts, ...postsData] : postsData);
            setTotal(totalCount);
            
            // 加载更多时更新页码
            if (isMore) {
              setPage(prev => prev + 1);
            }
            break;

          default:
            break;
        }
      }
    } catch (error) {
      console.error("数据获取失败:", error);
    } finally {
      setLoading(false);
      setIsLoadingMore(false);
      setInitialLoading(false);
    }
  };

  const handleBackToHomepage = () => {
    router.back();
  };

  // 渲染加载更多指示器
  const renderLoadingIndicator = () => {
    if (isLoadingMore) {
      return (
        <div style={loadingStyle}>
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-[#D6A7A1] mr-2"></div>
          <span>加载更多内容...</span>
        </div>
      );
    }
    
    // 已加载全部内容
    if (authorPosts.length >= total) {
      return (
        <div style={{ ...loadingStyle, color: "#999" }}>
          <span>已经到底啦</span>
        </div>
      );
    }
    
    return null;
  };

  const renderTabContent = () => {
    return (
      <div ref={contentRef}>
        <List
          itemLayout="horizontal"
          dataSource={authorPosts}
          renderItem={(item) => (
            <Link href={`/posts/${item.id}`} passHref prefetch>
              <List.Item style={cardStyle}>
                <div style={{ flex: 1 }}>
                  <Title level={4} style={{ margin: "0 0 8px 0", fontSize: 16, color: "#333" }}>
                    {item.title}
                  </Title>
                  <Text
                    type="secondary"
                    style={{ marginBottom: 8, fontSize: 12, color: "#7A6E6E" }}
                  >
                    作者：{author?.display_name}
                  </Text>
                  <Text
                    style={{
                      marginBottom: 12,
                      color: "#666",
                      lineHeight: 1.5,
                      fontSize: 14,
                      display: "-webkit-box",
                      "-webkit-line-clamp": 3,
                      "-webkit-box-orient": "vertical",
                      overflow: "hidden",
                    }}
                  >
                    {item.content}
                  </Text>
                  <Space style={{ marginTop: "auto" }}>
                    <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                      <span style={{ display: "flex", alignItems: "center" }}>
                        <span>{item.likes}</span>
                        <span style={{ marginLeft: 5 }}>👍</span>
                      </span>
                    </Button>
                    <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                      <span style={{ display: "flex", alignItems: "center" }}>
                        <span>{item.commentsCount || 0}</span>
                        <span style={{ marginLeft: 5 }}>💬</span>
                      </span>
                    </Button>
                    <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                      <span style={{ display: "flex", alignItems: "center" }}>
                        <span>{item.favourites}</span>
                        <span style={{ marginLeft: 5 }}>⭐</span>
                      </span>
                    </Button>
                  </Space>
                  <Text
                    type="secondary"
                    style={{
                      marginTop: 8,
                      fontSize: 10,
                      color: "#999",
                    }}
                  >
                    {item.createdAt}
                  </Text>
                </div>
              </List.Item>
            </Link>
          )}
        />
        
        {/* 加载更多指示器 */}
        {renderLoadingIndicator()}
      </div>
    );
  };

  // 滚动事件处理 - 当用户滚动到距离底部一定距离时加载更多
  const handleScroll = useCallback(() => {
    if (isLoadingMore) return;
    
    const contentElement = contentRef.current;
    if (!contentElement) return;
    
    const { scrollTop, scrollHeight, clientHeight } = contentElement;
    
    // 当滚动到距离底部100px时加载更多
    if (scrollTop + clientHeight >= scrollHeight - 100 && authorPosts.length < total) {
      fetchData(true);
    }
  }, [isLoadingMore, total, authorPosts.length]);

  // 组件挂载和卸载时的滚动事件监听
  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.addEventListener("scroll", handleScroll);
    }
    
    return () => {
      if (contentRef.current) {
        contentRef.current.removeEventListener("scroll", handleScroll);
      }
    };
  }, [handleScroll]);

  if (initialLoading) {
    return (
      <div 
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
          backgroundColor: "#F4EDEB"
        }}
      >
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-[#D6A7A1] mb-4"></div>
          <p className="text-[#7A6E6E] text-lg">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        background: "#F4EDEB",
        color: "#333333",
        minHeight: "100vh",
        padding: "20px",
      }}
    >
      {/* 页面顶部操作栏 */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          width: "100%",
          maxWidth: "1200px",
          padding: "0 16px",
          boxSizing: "border-box",
          zIndex: 10,
        }}
      >
        {/* 左侧图标区 */}
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          {/* 回到主页图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#7A6E6E",
              cursor: "pointer",
              transition: "color 0.3s"
            }}
            onClick={() => router.push("/homepage/home")}
            className="hover:text-[#D6A7A1]"
          >
            <HomeOutlined />
          </div>
          
          {/* 返回图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#7A6E6E",
              cursor: "pointer",
              transition: "color 0.3s"
            }}
            onClick={handleBackToHomepage}
            className="hover:text-[#D6A7A1]"
          >
            <LeftOutlined />
          </div>
        </div>
        
        {/* 右侧图标区 */}
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          {/* 私信作者图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#7A6E6E",
              cursor: "pointer",
              transition: "color 0.3s"
            }}
            onClick={() => router.push(`/messages/${authorId}`)}
            className="hover:text-[#D6A7A1]"
          >
            <MessageOutlined />
          </div>
          
          {/* 举报作者图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#d9534f",
              cursor: "pointer",
              transition: "color 0.3s"
            }}
            onClick={() => router.push(`/author/${authorId}/report`)}
            className="hover:text-[#E57373]"
          >
            <ExclamationCircleOutlined />
          </div>
        </div>
      </div>

      <Card
        style={{
          width: "90%",
          maxWidth: 1100,
          background: "white",
          border: "none",
          borderRadius: 20,
          margin: "20px auto",
          boxShadow: "0 4px 20px rgba(0, 0, 0, 0.08)",
          overflow: "hidden",
        }}
        title={
          <div style={{ display: "flex", alignItems: "center" }}>
            {/* 作者头像 */}
            <Avatar
              src={`http://120.26.138.4:3000${authorIcon}`}
              size={100}
              style={{
                margin: 16,
                boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
                border: "4px solid white",
                borderRadius: "50%",
              }}
            />
            
            {/* 作者名和简介 */}
            <div style={{ marginLeft: 16, flex: 1 }}>
              <p
                style={{
                  margin: 0,
                  color: "#333",
                  fontWeight: "bold",
                  fontSize: "24px",
                }}
              >
                {author.display_name}
              </p>
              <p style={{ margin: "8px 0 0 0", color: "#7A6E6E", fontSize: "16px" }}>
                {author.bio}
              </p>
            </div>
          </div>
        }
      >
        {/* 固定的菜单标签 */}
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            marginBottom: 16,
            borderBottom: "1px solid #eee",
            paddingBottom: 12,
          }}
        >
          <Button
            type="text"
            onClick={() => setActiveTab("posts")}
            style={{
              color: activeTab === "posts" ? "#D6A7A1" : "#7A6E6E",
              margin: "0 10px",
              fontSize: 16,
              fontWeight: activeTab === "posts" ? "bold" : "normal",
              padding: "8px 16px",
              transition: "all 0.3s",
              borderRadius: 20,
            }}
            className={activeTab === "posts" ? "bg-[#F4EDEB]" : ""}
          >
            帖子
          </Button>
        </div>

        {/* 内容区域 - 设置为可滚动 */}
        <div 
          style={{
            flex: 1,
            overflow: "auto",
            maxHeight: "calc(100vh - 350px)", // 设置最大高度，防止内容溢出
            padding: "0 20px 20px", // 底部padding为加载指示器留出空间
          }}
        >
          {renderTabContent()}
        </div>
      </Card>
    </div>
  );
}  